//
//  PlayerManager.m
//  AVPlayer(音频)
//
//  Created by Jason on 16/3/23.
//  Copyright © 2016年 Jason. All rights reserved.
//

#import "PlayerManager.h"

@interface PlayerManager ()

@property (nonatomic, strong) AVPlayer *myPlayer;

@end

@implementation PlayerManager

+ (PlayerManager *)shardedManager {
    static PlayerManager *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[PlayerManager alloc] init];
    });
    return player;
}

- (instancetype)init {
    if (self = [super init]) {
        self.myPlayer = [[AVPlayer alloc] init];
        _index = 0;
    }
    return self;
}
// 拿到外界传过来的数组之后就可以播放了
- (void)setMusicArray:(NSArray *)musicArray {
    _musicArray = musicArray;
    // 默认播放第0个
 //   _index = 0;
    // 使用AVPlayerItem可以获取歌曲更多信息 （总时间 播放进度）
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:musicArray[_index]]];
    [_myPlayer replaceCurrentItemWithPlayerItem:item];
     //   [_myPlayer play];
}

- (void)preMusic {
    NSInteger oldIndex = _index;
    _index -= 1;
    if (_index == -1) {
        _index = _musicArray.count - 1;
    }
    if (_playType == PlayTypeRandom) {
        if (_musicArray.count != 1) {
            do {
                _index = arc4random() % _musicArray.count;
            } while (oldIndex == _index);
        }
    }
    [self changeMusicWithIndex:_index];
}

- (void)playDidFinish {
    if (_playType == PlayTypeSingle) {
        [self seekToTime:0];
    }else {
        [self nextMusic];
    }
}

- (BOOL)isPlaying {
    // rate 0.0代表停止 1.0代表播放
    if (_myPlayer.rate == 0.0) {
        return NO;
    }
    return YES;
}

- (void)nextMusic {
    _index ++;
    if (_index == _musicArray.count) {
        _index = 0;
    }
    [self changeMusicWithIndex:_index];
}

- (void)play {
    [_myPlayer play];
}

- (void)pause {
    [_myPlayer pause];
}

- (NSInteger)currentTime {
    // 表示 AVPlayer 的时间都是 CMTime 类型的结构体，结构体中，valua代表的是总帧数 timescale代表多少帧
    if (_myPlayer.currentTime.timescale == 0) {
        return 0;
    }
    return _myPlayer.currentTime.value / _myPlayer.currentTime.timescale;
}

- (NSInteger)finishTime {
    CMTime time = _myPlayer.currentItem.duration;
    if (time.timescale == 0) {
        return 0;
    }
    return time.value / time.timescale;
}

- (void)seekToTime:(NSInteger)newTime {
    // 计算机识别歌曲进度的时候是按照帧数来计算的， 当前帧数 = 当前时间 * 每秒播放帧数
    [_myPlayer seekToTime:CMTimeMake(_myPlayer.currentTime.timescale * newTime, _myPlayer.currentTime.timescale)];
}

- (void)changeMusicWithIndex:(NSInteger)index {
    _index = index;
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:_musicArray[index]]];
    [_myPlayer replaceCurrentItemWithPlayerItem:item];
    [_myPlayer play];
}

@end










